BINARY = ngramtool

TEST_LDADD = \
	-lpthread \
	$(BINARY).a

CFLAGS = -Wall -Werror -std=c++0x
LDFLAGS = -static
OPTFLAGS = -O2
TEST_FLAGS = -g
LDADD =

SRCS = \
  istring.cc

HDRS = \
  istring.h \
  ngram.h \
  ngram_table.h

TESTS = \
	istring_test \
  ngram_table_test

all: depend $(BINARY) $(TESTS)

################################# BEGIN gtest ##################################

# Because gtest does some conditional compilation, the new, approved use case is
# to compile it inside the makefile for your project, which IMO is an unjust
# burden for small projects, and I'm quite grumpy about it.

GTEST_DIR = /usr/src/gtest
GTEST_INCLUDE_DIR = /usr/include
GTEST_HEADERS = $(GTEST_INCLUDE_DIR)/*.h $(GTEST_INCLUDE_DIR)/gtest/internal/*.h
GTEST_SRCS = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS)

gtest-all.o: $(GTEST_SRCS)
	g++ $(CPPFLAGS) -I$(GTEST_DIR) $(CFLAGS) -c $(GTEST_DIR)/src/gtest-all.cc

gtest_main.o: $(GTEST_SRCS)
	g++ $(CPPFLAGS) -I$(GTEST_DIR) $(CFLAGS) -c $(GTEST_DIR)/src/gtest_main.cc

gtest.a: gtest-all.o
	ar $(ARFLAGS) $@ $^

gtest_main.a: gtest-all.o gtest_main.o
	ar $(ARFLAGS) $@ $^

################################## END gtest ###################################

check: $(TESTS:%_test=%_test.stamp)

clean: .PHONY

.PHONY:
	rm -f *.o *.a *.dep *.stamp $(BINARY) $(TESTS)

depend: $(SRCS:%.cc=%.dep) $(TESTS:%_test=%_test.dep)

%.dep: %.cc
	gcc -MM $(CFLAGS) $*.cc > $*.dep

-include $(SRCS:%.cc=%.dep) $(TESTS:%_test=%_test.dep)

%.o: %.cc
	gcc -c $(CFLAGS) $(OPTFLAGS) $*.cc -o $*.o

$(BINARY).a: $(SRCS:%.cc=%.o) $(HDRS)
	ar crs $(BINARY).a $(SRCS:%.cc=%.o)

$(BINARY): $(BINARY).a main.cc
	g++ $(CFLAGS) $(OPTFLAGS) -o $(BINARY) main.cc $(BINARY).a $(LDFLAGS) $(LDADD)
	strip -s $(BINARY)

%_test.dep: %_test.cc $(BINARY).a $(GTEST_HEADERS)
	g++ -MM $(CFLAGS) $(TEST_FLAGS) $*_test.cc > $*_test.dep

%_test: %_test.cc $(BINARY).a $(GTEST_HEADERS) gtest_main.a
	g++ $(CFLAGS) $(TEST_FLAGS) gtest_main.a -o $*_test $*_test.cc $(TEST_LDADD) $(LDADD)

%_test.stamp: %_test
	./$*_test
	touch $*_test.stamp
